//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.Common.Utils;
using System.Xml;
using System.Web.Hosting;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;
using System.Web.UI;
using NopSolutions.NopCommerce.BusinessLogic.Services;

namespace NopSolutions.NopCommerce.Web.Modules
{
    public partial class HeaderMenuControl : BaseNopFrontendUserControl
    {
        private readonly ICategoryService _categoryService;
        private readonly IProductService _productService;
        private readonly ISettingService _settingService;
        private IBlogService _blogService;
        private IForumService _forumService;
        private Category _currentCategory;

        public HeaderMenuControl() {
            _categoryService = IoC.Resolve<ICategoryService>();
            _productService = IoC.Resolve<IProductService>();
            _settingService = IoC.Resolve<ISettingService>();
            _blogService = IoC.Resolve<IBlogService>();
            _forumService = IoC.Resolve<IForumService>();
        }

        protected override void OnInit(EventArgs e) {
            Load += new EventHandler(HeaderMenuControl_Load);

            base.OnInit(e);
        }

        void HeaderMenuControl_Load(object sender, EventArgs e) {
            string cssClass = "menu";
            if (!string.IsNullOrWhiteSpace(CssClass))
                cssClass += " " + CssClass;

            var sb = new StringBuilder();
            sb.AppendFormat("<ul class=\"{0}\">", cssClass);

            var selected = string.Empty;
            if (Request.Url.AbsolutePath.Equals("/") || Request.Url.AbsolutePath.ToLower().Equals("/default.aspx")) {
                selected = "active";
            }

            sb.AppendFormat("<li id=\"home\" class=\"{0}\"><a href=\"{1}\" class=\"main\">{2}</a></li>", selected, Page.ResolveUrl("~/"), GetLocaleResourceString("Content.HomePage"));

            // categories
            var categories = _categoryService.GetAllCategoriesByParentCategoryId(0);
            foreach (var category in categories) {
                BuildCategoryNavigationRecursive(category, sb);
            }

            sb.Append("</ul>");
            litMenu.Text = sb.ToString();
        }


        //protected void BuildCategoryNavigationRecursive(int rootCategoryId, StringBuilder sb) {
        protected void BuildCategoryNavigationRecursive(Category category, StringBuilder sb) {
            //foreach (var category in _categoryService.GetAllCategoriesByParentCategoryId(rootCategoryId)) {
            string cssClass = string.Empty;

            if (category.HasChildren) {
                cssClass = "has-children";
            }

            if (CurrentCategory != null && CurrentCategory.CategoryId == category.CategoryId)
                cssClass += " active";

            if (!string.IsNullOrEmpty(cssClass)) {
                cssClass = "class=\"" + cssClass + "\"";
            }

            string id = string.Empty;
            if (category != null)
                id = "id=" + SEOHelper.GetCategorySEName(category);

            sb.Append(string.Format("<li {0} {1}>", cssClass, id));

            // show no. of products near category name?
            string catname = string.Empty;
            if (_settingService.GetSettingValueBoolean("display.products.showcategoryproductnumber")) {
                //display category name with assigned products number
                int numberofproducts = GetNumberOfProducts(category, _settingService.GetSettingValueBoolean("display.products.showcategoryproductnumber.includesubcategories"));
                catname = string.Format("{0} <span class=\"blue label\">{1}</span>", category.LocalizedName, numberofproducts);
            } else {
                //display only category name
                catname = category.LocalizedName;
            }

            string categoryUrl = SEOHelper.GetCategoryUrl(category);

            sb.Append(string.Format("<a href=\"{0}\" class=\"{1}\">{2}</a>", categoryUrl, category.ParentCategoryId == 0 ? "main" : "", catname));

            if (category.HasChildren) {
                sb.Append("<ul class=\"flyout\">>");

                foreach (var childCategory in category.ChildCategories) {
                    BuildCategoryNavigationRecursive(childCategory, sb);
                }

                sb.Append("</ul>");
            }

            sb.Append("</li>");
            //}
        }

        protected int GetNumberOfProducts(Category category, bool includeSubCategories) {
            int numberOfProducts = 0;
            var products = _productService.GetAllProducts(category.CategoryId,
                        0, 0, null, null, null, string.Empty, false, 1, 0,
                        null, ProductSortingEnum.Position, out numberOfProducts);

            if (includeSubCategories) {
                var subCategories = _categoryService.GetAllCategoriesByParentCategoryId(category.CategoryId);
                foreach (var subCategory in subCategories) {
                    int tmp1 = GetNumberOfProducts(subCategory, includeSubCategories);
                    numberOfProducts += tmp1;
                }
            }
            return numberOfProducts;
        }

        public string CssClass { get; set; }

        public Category CurrentCategory {
            get {
                if (_currentCategory == null) {
                    _currentCategory = _categoryService.GetCategoryById(CategoryId);
                    if (_currentCategory == null) {
                        var product = _productService.GetProductById(ProductId);
                        if (product != null) {
                            var productCategories = product.ProductCategories;
                            if (productCategories.Count > 0) {
                                _currentCategory = productCategories[0].Category;
                            }
                        }
                    }
                }
                return _currentCategory;
            }
        }

        public int CategoryId {
            get { return CommonHelper.RouteStringInt("categoryId"); }
        }

        public int ProductId {
            get { return CommonHelper.RouteStringInt("productId"); }
        }
    }
}